package hasthi.actuators.actions;

import hasthi.actuators.CreateServiceAction;
import hasthi.actuators.ResourceBasedAction;
import hasthi.actuators.SystemConfig;
import hasthi.common.HasthiException;
import hasthi.config.ResourceProfile;
import hasthi.metamodel.resource.ManagedResource;

public class MigrateAction extends ResourceBasedAction {
    private String name;
    private boolean shutDownRunning = true;
    private String targetHost;

    public MigrateAction(ManagedResource resource) {
        super(resource);
        name = "MigrateAction#" + resource.getName();
    }

    @Override
    public void execute() throws HasthiException {
        if (shutDownRunning) {
            ShutDownAction shutDownAction = new ShutDownAction(resource);
            shutDownAction.init(actionContext);
            shutDownAction.execute();
        }
        // Action command may refer to checkpoint location via
        // ${Old.CheckPointLocation}
        CreateServiceAction createServiceAction = new CreateServiceAction(resource);
        if (targetHost != null) {
            createServiceAction.setTargetHost(targetHost);
        }
        createServiceAction.init(actionContext);
        createServiceAction.execute();
        // TODO assign resource to be monitored, this work only for databases
        SystemConfig systemConfig = actionContext.getSystemConfig();
        ResourceProfile resourceProfile = systemConfig.getResourceProfile(resource.getQName());
        if (resourceProfile.getMonitoring() != null) {
            if (resource.getName().contains("MySQL")) {
                resourceProfile.getMonitoring().setHostName(createServiceAction.getTargetHost());
            } else {
                resourceProfile.getMonitoring().setEndpointAddress(
                        createServiceAction.getNewServiceUrl());
            }
        }
        MngActionUtils.sendNewRequestForMonitoring(resourceProfile);
    }

    @Override
    public String getActionID() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }

    public void setShutDownRunning(boolean shutDownRunning) {
        this.shutDownRunning = shutDownRunning;
    }

    public void setTargetHost(String targetHost) {
        this.targetHost = targetHost;
    }
}
